import React, { useEffect, useState } from "react";
import { Box, Typography, Avatar } from "@mui/material";

type MessageProps = {
  sender: "user" | "assistant";
  text: string;
};
// 打字机效果组件
const TypingEffect = ({ text }: { text: string }) => {
  if (text == "...") return "loading...";
  console.log(text);
  const [displayedText, setDisplayedText] = useState("");

  useEffect(() => {
    let index = 0;
    const intervalId = setInterval(() => {
      if (index < text.length - 1) {
        setDisplayedText((prev) => prev + text[index]);
        index++;
      } else {
        clearInterval(intervalId);
      }
    }, 10); // 设置字符显示的速度（毫秒）

    return () => clearInterval(intervalId);
  }, [text]);

  return <span>{displayedText}</span>;
};
// Message 组件，用于显示每条消息
const Message: React.FC<MessageProps> = ({ sender, text }) => {
  // 设置头像图片和用户名
  const userAvatar = "/user.png";
  const aiAvatar = "/chatGPT.png";
  const userName = sender === "user" ? "You" : "ChatGPT";

  return (
    <Box
      sx={{
        display: "flex",
        justifyContent: "flex-start",
        mb: 2,
      }}
    >
      {sender === "assistant" && (
        <Avatar
          src={aiAvatar}
          alt="AI Avatar"
          sx={{ width: 40, height: 40, mr: 2 }}
        />
      )}
      {sender === "user" && (
        <Avatar
          src={userAvatar}
          alt="User Avatar"
          sx={{ width: 40, height: 40, mr: 2 }}
        />
      )}
      <Box
        sx={{
          display: "flex",
          flexDirection: "column",
          width: "100%",
        }}
      >
        <Typography variant="caption">{userName}</Typography>
        <Typography
          sx={{
            color: "#000",
            maxWidth: "70%",
            whiteSpace: "pre-wrap", // 保留换行和空格
            wordBreak: "break-word", // 处理长单词换行
          }}
        >
          {sender === "user" ? text : <TypingEffect text={text} />}
        </Typography>
      </Box>
    </Box>
  );
};

export default Message;
